package a66weding.com.jiehuntong.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.xutils.common.util.DensityUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

import a66weding.com.jiehuntong.R;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/5/18
 * @description :
 */
public class MyListView extends ListView {

    private View footer;
    private LinearLayout header;
    private View newstopview;

    private RelativeLayout bottomRelay;
    private ImageView imgUp;
    private ImageView imgLoading;
    private TextView bottomText;
    private LinearLayout llay_loadmore_view;

    private  float listViewOnScreenY = -1;
    private ImageView imgState;//加载完的状态结果


    // 初始状态
    public static final int INIT = 0;
    // 释放刷新
    public static final int RELEASE_TO_REFRESH = 1;
    // 正在刷新
    public static final int REFRESHING = 2;
    // 释放加载
    public static final int RELEASE_TO_LOAD = 3;
    // 正在加载
    public static final int LOADING = 4;
    // 操作完毕
    public static final int DONE = 5;
    //往上拉的状态
    public static final int PULL=6;
    //往上拉的状态
    public static final int PULLUP=7;
    //往下拉的状态
    public static final int PULLDOWN=8;

    //发延迟消息
    public static final int LOADINGTIME=9;
    public static final int LOADINGTIME2=10;


    // 当前状态
    private int state = INIT;
    // 过滤多点触碰
    private int mEvents;
    private int headerHeight;
    private int topDistance;
    private RotateAnimation upAnimation;
    private RotateAnimation downAnimation;

    private int footerHeight;//底部状态栏的高度

    private OnRefreshingListener onRefreshingListener;
    private int lastVisiblePosition;
    private int distance;
    private boolean isStartY;
    private int paddingdip;

    private boolean isRemark; // 标记是否滑动到底部

    public MyListView(Context context) {
        super(context);
        initFooterView(context);
        initAnimation(context);
    }


    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initFooterView(context);
        initAnimation(context);
    }

    public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initFooterView(context);
        initAnimation(context);
    }




    /**
     * 初始化控件
     */
    private void initFooterView(Context context) {
        footer = View.inflate(context,R.layout.footer_refreshlistview, null);
        bottomRelay = (RelativeLayout) footer.findViewById(R.id.rlay_loadmore_view);
        imgUp = (ImageView) footer.findViewById(R.id.iv_pullup_myview);
        imgLoading = (ImageView) footer.findViewById(R.id.iv_loading_myview);
        bottomText = (TextView) footer.findViewById(R.id.tv_loadstate_myview);
        llay_loadmore_view = (LinearLayout) footer.findViewById(R.id.llay_loadmore_view);

        llay_loadmore_view.measure(0,0);
        footerHeight = llay_loadmore_view.getMeasuredHeight();

        paddingdip = DensityUtil.px2dip(20);
        llay_loadmore_view.setPadding(0,0,0, paddingdip);


        this.addFooterView(footer);

        setOnScrollListener(monScrollListener);

    }


    /**
     * 重写onTouchEvent方法，实现头部刷新状态的显示
     */
    int startY;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int eventY= (int) event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                startY=eventY;
                break;
            case MotionEvent.ACTION_MOVE:
                int dY=eventY-startY;

                if(isRemark) {//上拉加载
                    //如果正在加载-联网，不用加载
                    if(state==LOADING) {
                        break;
                    }

                    if(!isStartY){
                        startY=eventY;
                        isStartY=true;
                    }
                    int mathdY=Math.abs(dY);


                    if(dY>0) {//手指往下滑
                        llay_loadmore_view.setPadding(0,0,0,paddingdip);
                        if(state!=INIT){
                            state=INIT;
                            refreshFooterViewState();

                        }
                    }else if(dY<0){//手指往上滑
                        if(mathdY>footerHeight) {
                            llay_loadmore_view.setPadding(0,0,0,mathdY-footerHeight);
                            if(state!=RELEASE_TO_LOAD) {
                                state=RELEASE_TO_LOAD;
                                refreshFooterViewState();
                            }
                        }else if(mathdY<footerHeight){
                            if(state!=INIT){
                                state=INIT;
                                refreshFooterViewState();
                            }
                        }

                    }
                }

                break;

            case MotionEvent.ACTION_UP:
                if(state==RELEASE_TO_REFRESH && state!=REFRESHING) {
                    state=REFRESHING;
                    //完全显示
                    if(onRefreshingListener!=null) {
                        onRefreshingListener.onRefresh();

                    }
                    handler.sendEmptyMessageDelayed(LOADINGTIME, 5000);
                }else if(state==INIT){
                    //回到初始状态
                    llay_loadmore_view.setPadding(0,0,0,paddingdip);
                }else if(state==RELEASE_TO_LOAD && state!=LOADING){
                    state=LOADING;
                    //完全显示
                    llay_loadmore_view.setPadding(0,0,0,paddingdip);
                    refreshFooterViewState();
                    if(onRefreshingListener!=null) {
                        onRefreshingListener.onLoadMore();
                    }
                    handler.sendEmptyMessageDelayed(LOADINGTIME, 5000);
                }
                break;

        }
        return super.onTouchEvent(event);
    }

    /**
     * 更新底部加载更多刷新状态
     */
    private void refreshFooterViewState() {
        switch (state){
            case INIT://正常状态
                bottomText.setText("上拉加载更多. . .");
                imgUp.startAnimation(downAnimation);
                break;
            case RELEASE_TO_LOAD://释放刷新
                bottomText.setText("释放立即加载");
                imgUp.startAnimation(upAnimation);
                break;
            case LOADING://正在加载
                bottomText.setText("正在加载...");
                imgUp.clearAnimation();
                imgUp.setVisibility(View.GONE);

                imgLoading.setVisibility(View.VISIBLE);
                break;

        }
    }


    /**
     * 当刷新完成后，状态复原
     * @param isPullDownRefresh
     */
    public void onRefreshFinish(boolean isPullDownRefresh) {
        if(isPullDownRefresh) {
            handler.sendEmptyMessageDelayed(LOADINGTIME2,3000);
        }else{
            bottomText.setText("不好意思，数据请求失败...");
            handler.sendEmptyMessageDelayed(LOADINGTIME2,3000);
        }
        state=INIT;
        //刷新栏复位

        llay_loadmore_view.setPadding(0,0,0,paddingdip);
        imgLoading.setVisibility(View.GONE);
        imgUp.setVisibility(View.VISIBLE);
        imgUp.clearAnimation();

    }


    /**
     * ListView的滚动状态监听
     */
    OnScrollListener monScrollListener = new OnScrollListener() {
        /**
         * 静止->滚动
         * 惯性滚动->静止
         * 滚动->惯性滚动
         * @param view
         * @param scrollState
         */
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        /**
         * 滚动过程中回调的方法
         * @param view
         * @param firstVisibleItem
         * @param visibleItemCount
         * @param totalItemCount
         */
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                             int totalItemCount) {
            if(getLastVisiblePosition()==totalItemCount-1){
                isRemark=true;
            }else{
                isRemark=false;
            }


        }
    };

    private CharSequence sysTemTimeText() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeText = simpleDateFormat.format(new Date());
        return timeText;
    }




    /**
     *刷新箭头旋转动画集
     */
    public void initAnimation(Context context){
        //向上旋转
        upAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        upAnimation.setDuration(500);
        upAnimation.setFillAfter(true);
        //向下旋转
        downAnimation = new RotateAnimation(-180, -360, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        downAnimation.setDuration(500);
        downAnimation.setFillAfter(true);
    }



    public void setOnRefreshingListener(OnRefreshingListener onRefreshing) {
        this.onRefreshingListener = onRefreshing;
    }

    public interface OnRefreshingListener{
        /**
         * 刷新
         */
        public abstract void onRefresh();
        /**
         * 加载更多
         */
        public abstract void onLoadMore();
    }



    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==LOADINGTIME) {
                onRefreshFinish(false);
            }else if(msg.what==LOADINGTIME2){
//                tv_time_headrefresh.setText("下拉刷新");
                bottomText.setText("上拉加载更多");
            }
        }
    };

    public  void destoryMsg(){
        handler.removeCallbacksAndMessages(null);
    }



}
